﻿#region License
// Copyright (c) 2012 Mund Consulting Ltd
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Navigation;
using System.Web.UI.WebControls;

namespace SharePoint.Foundation.Publishing
{
    public partial class Navigation : LayoutsPageBase
    {
        const string constIconFolderPath = "/_Layouts/Images/";
        const string constDefaultIconPath = "/_Layouts/Images/itdl.png";
        const string constAddCommand = "add";
        const string constEditCommand = "Edit";
        const string constPropertyTarget = "Target";
        const string constTargetBlankValue = "_blank";
        const string constPropertyDisplay = "Display";
        const string constDisplayValueNone = "None";
        const string constDisplayValueBlock = "Block";

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {

                LoadTree();
                if (SPContext.Current.Web == SPContext.Current.Site.RootWeb)
                {
                    chBxInheritParent.Enabled = false;
                }
            }

        }

        void LoadTree()
        {

            SPWeb curWeb = SPContext.Current.Web;
            if (!curWeb.Navigation.UseShared)
            {
                SPNavigationNodeCollection pnodes = curWeb.Navigation.TopNavigationBar;
                TreeNode tNode;
                foreach (SPNavigationNode node in pnodes)
                {

                    tNode = new TreeNode(node.Title, node.Id.ToString(), GetIconFile(node));

                    trvTopNav.Nodes.Add(tNode);
                    GetChildNode(node, tNode);
                }
                trvTopNav.ExpandAll();
            }
            else
            {
              
                chBxInheritParent.Checked = true;
            }
        }



        protected void GetChildNode(SPNavigationNode node, TreeNode tnode)
        {
            SPWeb curWeb = SPContext.Current.Web;
            TreeNode ptNode = tnode;
            SPNavigationNodeCollection chNodes = node.Children;
            foreach (SPNavigationNode chNode in chNodes)
            {

                tnode = new TreeNode(chNode.Title, chNode.Id.ToString(), GetIconFile(chNode));
                ptNode.ChildNodes.Add(tnode);
                GetChildNode(chNode, tnode);
            }
        }



        string GetIconFile(SPNavigationNode node)
        {
            SPWeb curWeb = SPContext.Current.Web;
            string iconFile = string.Empty;
            try
            {
                SPFile file = curWeb.GetFile(node.Url);
                if (file.InDocumentLibrary)
                    iconFile = constIconFolderPath + file.IconUrl;
                else
                {
                    iconFile = constDefaultIconPath;
                }
            }

            catch
            {
                iconFile = constDefaultIconPath;
            }

            return iconFile;
        }


        protected void AddTitle(object sender, EventArgs e)
        {
            try
            {
                SPWeb curWeb = SPContext.Current.Web;
                SPNavigationNodeCollection pNodes = curWeb.Navigation.TopNavigationBar;
                SPNavigationNode spNode, newNode = null;
                if (btnAddTitle.CommandArgument == constAddCommand)
                {
                    newNode = new SPNavigationNode(tbxTitle.Text, tbxUrl.Text, chBxExternalLink.Checked);
                    if (trvTopNav.SelectedValue != string.Empty)
                    {
                        spNode = pNodes.Navigation.GetNodeById(int.Parse(trvTopNav.SelectedValue));
                        spNode.Children.AddAsLast(newNode);

                        spNode.Update();
                    }
                    else
                    {
                        pNodes.AddAsLast(newNode);

                    }
                    if (chBxNewWindow.Checked == true)
                    {
                        if (newNode.Properties.ContainsKey(constPropertyTarget))
                        {
                            newNode.Properties.Remove(constPropertyTarget);
                        }
                        // node.Properties.Add("Target", "_blank");
                        newNode.Properties[constPropertyTarget] = constTargetBlankValue;
                    }
                }

                else if (btnAddTitle.CommandArgument == constEditCommand)
                {

                    newNode = pNodes.Navigation.GetNodeById(Convert.ToInt32(trvTopNav.SelectedValue));
                    newNode.Title = tbxTitle.Text;
                    newNode.Url = tbxUrl.Text;

                }

                newNode.Update();

                trvTopNav.Nodes.Clear();
                LoadTree();
                ClearBoxes();
              
            }
            catch (Exception er)
            {
                error.Visible = true;
                error.ToolTip = er.Message;
                AddTitlePanel.Style.Add(constPropertyDisplay, constDisplayValueBlock);
                //Response.Write("javascript:SP.UI.Notify.addNotification('itworks');");
            }

        }
        protected void DeleteNode(object sender, EventArgs e)
        {
            SPWeb curWeb = SPContext.Current.Web;
            SPNavigationNodeCollection pnodes = curWeb.Navigation.TopNavigationBar;
            SPNavigationNode node = pnodes.Navigation.GetNodeById(Convert.ToInt32(trvTopNav.SelectedValue));

            if (node.Parent.Id == pnodes.Parent.Id)
            {
                pnodes.Delete(node);
            }
            else
            {
                node.Parent.Children.Delete(node);
            }


            trvTopNav.Nodes.Clear();
            LoadTree();
            Response.Redirect(HttpContext.Current.Request.Url.ToString());
            
        }



        protected void GoDown(object sender, EventArgs e)
        {
            SPWeb curWeb = SPContext.Current.Web;
            SPNavigationNodeCollection pnodes = curWeb.Navigation.TopNavigationBar;
            SPNavigationNode currentNode = pnodes.Navigation.GetNodeById(Convert.ToInt32(trvTopNav.SelectedValue));
            SPNavigationNode prevNode;

            int counter = 0;

            foreach (SPNavigationNode childNode in currentNode.Parent.Children)
            {

                if (childNode.Id == currentNode.Id)
                {
                    break;
                }
                counter++;
            }

            string path = trvTopNav.SelectedNode.ValuePath;
            if (counter != currentNode.Parent.Children.Count - 1)
            {
                prevNode = currentNode.Parent.Children[counter + 1];
                currentNode.Move(currentNode.Parent.Children, prevNode);
            }


            trvTopNav.Nodes.Clear();
            LoadTree();
            trvTopNav.FindNode(path).Selected = true;

        }


        protected void GoUp(object sender, EventArgs e)
        {
            SPWeb curWeb = SPContext.Current.Web;
            SPNavigationNodeCollection pnodes = curWeb.Navigation.TopNavigationBar;
            SPNavigationNode currentNode = pnodes.Navigation.GetNodeById(Convert.ToInt32(trvTopNav.SelectedValue));
            SPNavigationNode prevNode;

            int counter = 0;

            foreach (SPNavigationNode childNode in currentNode.Parent.Children)
            {
                if (childNode.Id == currentNode.Id)
                {
                    break;
                }
                counter++;
            }

            string path = trvTopNav.SelectedNode.ValuePath;

            if ((counter - 2) < 0)
            {
                SPNavigationNodeCollection parnodes = currentNode.Parent.Children;

                currentNode.MoveToFirst(parnodes);

            }
            else
            {
                prevNode = currentNode.Parent.Children[counter - 2];
                currentNode.Move(currentNode.Parent.Children, prevNode);
            }

            trvTopNav.Nodes.Clear();
            LoadTree();
            trvTopNav.FindNode(path).Selected = true;
        }


        protected void EditNode(object sender, EventArgs e)
        {
            if (trvTopNav.SelectedValue != null)
            {

                SPWeb curWeb = SPContext.Current.Web;
                SPNavigationNodeCollection pnodes = curWeb.Navigation.TopNavigationBar;
                SPNavigationNode node = pnodes.Navigation.GetNodeById(Convert.ToInt32(trvTopNav.SelectedValue));
                AddTitlePanel.Style.Add(constPropertyDisplay, constDisplayValueBlock);
                tbxTitle.Text = node.Title;
                tbxUrl.Text = node.Url;
                chBxExternalLink.Checked = node.IsExternal;
                chBxExternalLink.Enabled = false;
                btnAddTitle.CommandArgument = constEditCommand;

            }
        }
        protected void Cancel(object sender, EventArgs e)
        {
            ClearBoxes();
        }

        protected void InheritParentNavigation(object sender, EventArgs e)
        {
            SPWeb curWeb = SPContext.Current.Web;
            if (chBxInheritParent.Checked)
            {
                curWeb.Navigation.UseShared = true;
            }
            else
            {
                curWeb.Navigation.UseShared = false;
            }
            curWeb.Update();
            trvTopNav.Nodes.Clear();
            LoadTree();
           
        }

        void ClearBoxes()
        {
            tbxTitle.Text = string.Empty;
            tbxUrl.Text = string.Empty;
            chBxNewWindow.Checked = false;
            chBxExternalLink.Checked = false;
            AddTitlePanel.Style.Add(constPropertyDisplay, constDisplayValueNone);
            btnAddTitle.CommandArgument = constAddCommand;
            error.Visible = false;
            chBxExternalLink.Enabled = true;
        }
    }
}
